package com.hsq.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;


public class SocketTCP01Server {
    public static void main(String[] args) throws IOException {
        //1.在本机监听9999端口，等待连接
        //注意：要求本机没有其他服务在监听端口9999
        //这个ServerSocket 可以通过accept返回多个Socket[多个客户端连接服务器并发]
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("服务端在9999端口监听，等待连接");
        //等待连接,当客户端没有连接端口9999时，程序会阻塞
        Socket socket = serverSocket.accept();
        System.out.println("Server socket = " + socket.getClass());
        InputStream inputStream = socket.getInputStream();
        byte[] buf = new byte[1024];
        int readLine = 0;
        while ((readLine = inputStream.read(buf)) != -1) {
            System.out.println(new String(buf, 0, readLine));
        }
        //同时给client也发送信息
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("Hello Client".getBytes());
        //设置结束标志
        socket.shutdownOutput();

        outputStream.close();
        serverSocket.close();
        socket.close();
        inputStream.close();
        System.out.println("Srever exit");
    }
}
